package com.tempjob.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anwen.mongo.annotation.transactional.MongoTransactional;
import com.tempjob.app.controller.model.CompanyResult;
import com.tempjob.app.controller.model.ListResult;
import com.tempjob.app.controller.model.PolicyResult;
import com.tempjob.common.businesss.mongo.entity.CompanyInfo;
import com.tempjob.common.businesss.mongo.entity.JobCategory;
import com.tempjob.common.businesss.mongo.entity.JobInfo;
import com.tempjob.common.businesss.mongo.entity.PolicyContent;
import com.tempjob.common.businesss.service.MongoBeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author hui
 **/
@RequestMapping("/sys/import")
@RestController
@Api(tags = "数据导入")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class ImportController {

    @Autowired
    private MongoBeanUtil mongoBeanUtil;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping(value = "/jobMajor")
    @ApiOperation(value = "jobMajor", response = Boolean.class)
    public Object jobMajor() throws IOException {
        File dict = new File("D:/Desktop/gov/temp_job/job_major.txt");
        byte[] fileContent = FileCopyUtils.copyToByteArray(new FileInputStream(dict));
        // 将字节转换为字符串
        String jsonAsString = new String(fileContent, StandardCharsets.UTF_8);
        jobMajor listPage = JSON.parseObject(jsonAsString, jobMajor.class);
        for (Major datum : listPage.getData()) {
            addMajor(null, datum);
        }
        return true;
    }

//    @PostMapping(value = "/test")
//    @ApiOperation(value = "test", response = Boolean.class)
//    public Object test() throws IOException {
//        List<JobInfo> jobs = mongoBeanUtil.getJobInfoService().list();
//        for (JobInfo job : jobs) {
//            job.setLocation(new Point(new Position(job.getLatitude(), job.getLongitude())));
//            mongoBeanUtil.getJobInfoService().updateById(job);
//        }
//        return true;
//
//    }


    private void addMajor(String parentId, Major major) {
        JobCategory jobMajor = new JobCategory();
        jobMajor.setParentId(parentId);
        jobMajor.setCategoryName(major.getMajorTitle());
        mongoBeanUtil.getJobCategoryService().save(jobMajor);
        if (major.getChildren() != null && !major.getChildren().isEmpty()) {
            for (Major child : major.getChildren()) {
                addMajor(jobMajor.getId(), child);
            }
        }
    }

    @Data
    public static class jobMajor {
        private boolean success;
        private int code;
        private String msg;
        private List<Major> data;
    }

    @Data
    public static class Major {
        private String majorId;
        private String majorTitle;
        private int parentId;
        private int state;
        private String createUser;
        private long createTime;
        private List<Major> children;
    }


    @PostMapping(value = "/company")
    @ApiOperation(value = "company", response = Boolean.class)
    @MongoTransactional
    public Object company() {

        ListResult listData = restTemplate.getForObject("https://api.weijiuye.com.cn/job/order/order_list?pageNum=1&pageSize=50&hierarchy=C&lat=30.197616&lng=103.506539&sortField=distance&source=1", ListResult.class);
//        System.out.println(JSON.toJSONString(listData));
        List<ListResult.Result> list = listData.getData().getResult();
        for (ListResult.Result result : list) {
            String orgCode = result.getOrg().getHierarchy();
            CompanyResult companyInfo = restTemplate.getForObject("https://api.weijiuye.com.cn/job/order/query_order?lat=30.197616&lng=103.506539&orderId=" + result.getOrderId() + "&hierarchy=" + orgCode, CompanyResult.class);
            CompanyResult.Org companyOnline = companyInfo.getData().getOrg();

            CompanyInfo company = mongoBeanUtil.getCompanyInfoService().lambdaQuery().eq(CompanyInfo::getCompanyName, companyOnline.getOrgName()).one();
            if (company == null) {
                company = new CompanyInfo();
                company.setCompanyName(companyOnline.getOrgName());
                company.setCompanyLogo(companyOnline.getOrgLogo());
                company.setCompanyStatus(1);
                company.setUserId("67343d6362a7430ab13b1789");
//                company.setRegisterDate(companyOnline.getRegDate());
//                company.setCompanyType(2);
                company.setRegisterAddress(result.getStreet());
                company.setCompanyAddress(result.getAddressTitle());
                company.setCompanyScale(companyOnline.getScale());
                company.setSocialCreditCode(companyOnline.getOrgCode());
                if (StringUtils.isNotBlank(companyInfo.getData().getPostImg())) {
                    JSONObject postImg = JSON.parseObject(companyInfo.getData().getPostImg());
                    String imgsTring = postImg.getString("values");
                    if (StringUtils.isNotBlank(imgsTring)) {
                        List<String> imgs = JSON.parseArray(imgsTring, String.class);
                        company.setDescImages(imgs);
                    }
                }
                company.setLatitude(StringUtils.isBlank(result.getLat()) ? null : Double.valueOf(result.getLat()));
                company.setLongitude(StringUtils.isBlank(result.getLng()) ? null : Double.valueOf(result.getLng()));
                company.setCompanyDesc(companyOnline.getIntro());
                String welfare = result.getWelfare();
                company.setCompanyWelfare(JSON.parseArray(welfare, String.class));
                mongoBeanUtil.getCompanyInfoService().save(company);
            }
            JobInfo job = mongoBeanUtil.getJobInfoService().lambdaQuery().eq(JobInfo::getJobTitle, result.getPostTitle()).eq(JobInfo::getCompanyId, company.getId()).one();
//            if (job == null) {
//                job = new JobInfo();
//                WorkDay workDay = restTemplate.getForObject("https://api.weijiuye.com.cn/job/order/query_date_num?orderId=" + result.getOrderId() + "&hierarchy=" + orgCode, WorkDay.class);
//                if (workDay != null) {
//                    List<WorkDayModel> workDayModels = new ArrayList<>();
//                    for (WorkDay.ResultData day : workDay.getData()) {
//                        workDayModels.add(new WorkDayModel(day.getDate(), day.getNum(), 0));
//                    }
//                    job.setWorkDayList(workDayModels);
//                }
//                job.setJobTitle(result.getPostTitle());
//                job.setJobType(1);
//                job.setJobCategory(result.getMajorTitle());
//                job.setJobContent(companyInfo.getData().getIntro());
//                job.setCompanyId(company.getId());
//                job.setCompanyName(company.getCompanyName());
//                job.setContactName(companyInfo.getData().getCreateUserData().getUserName());
//                job.setContactPhone(companyInfo.getData().getCreateUserData().getPhone());
//                job.setPublishUserId("67343d6362a7430ab13b1789");
//                job.setJobStatus(2);
//                job.setJobType(1);
//                job.setDescImages(company.getDescImages());
//                if (StringUtils.isNotBlank(companyInfo.getData().getWelfare())) {
//                    job.setWelfareTags(JSON.parseArray(companyInfo.getData().getWelfare(), String.class));
//                }
//                job.setSalary(companyInfo.getData().getMoney());
//                job.setSalaryType(companyInfo.getData().getPayMode());
//                job.setSettlementType(companyInfo.getData().getPayMode());
//                job.setJobAddress(companyInfo.getData().getAddressTitle());
//                job.setStartDate(result.getStartDate());
//                job.setEndDate(result.getEndDate());
//                job.setIco(company.getCompanyLogo());
//
//                mongoBeanUtil.getJobInfoService().save(job);
//            }


        }
        return true;
    }

    @PostMapping(value = "/policy")
    @ApiOperation(value = "policy", response = Boolean.class)
    public Object policy() {
        PolicyResult listData = restTemplate.getForObject("https://cdjy.cdrsigc.com/article/article_list?pageNum=1&pageSize=100&sortField=joinUpdateTime&sortBy=false&query=&categoryIds=1568011019082041&orgId=1507610150543662", PolicyResult.class);
        List<PolicyResult.Result> policyList = listData.getData().getResult();
        for (PolicyResult.Result result : policyList) {
            PolicyContent policy = new PolicyContent();
            policy.setTitle(result.getArticleTitle());
            policy.setContent("");
            policy.setPolicyTime(result.getJoinUpdateTime());
            policy.setUrl("https://cdjy.cdrsigc.com/pages/article/detail?articleId=" + result.getArticleId() + "&articleOrgId=" + result.getArticleOrgId());
            mongoBeanUtil.getPolicyContentService().save(policy);
        }
        return true;

    }


}
